package com.ybb.seckilldemo.rabbitmq;

import com.ybb.seckilldemo.pojo.SeckillMessage;
import com.ybb.seckilldemo.pojo.SeckillOrder;
import com.ybb.seckilldemo.pojo.User;
import com.ybb.seckilldemo.service.Impl.GoodsServiceImpl;
import com.ybb.seckilldemo.service.Impl.OrderServiceImpl;
import com.ybb.seckilldemo.utils.JsonUtil;
import com.ybb.seckilldemo.vo.GoodsVo;
import com.ybb.seckilldemo.vo.RespBean;
import com.ybb.seckilldemo.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 消息消费者
 */
@Service
@Slf4j
public class MQReceiver {
    @Autowired
    private GoodsServiceImpl goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderServiceImpl orderService;

//    @RabbitListener(queues = "queue")
//    public void receive(Object msg) {
//        log.info("接收消息"+msg);
//    }
//
//    @RabbitListener(queues = "queue_fanout01")
//    public void receive01(Object msg) {
//        log.info("QUEUE01接收消息"+msg);
//    }
//
//    @RabbitListener(queues = "queue_fanout02")
//    public void receive02(Object msg) {
//        log.info("QUEUE02接收消息"+msg);
//    }
//
//    @RabbitListener(queues = "queue_direct03")
//    public void receive03(Object msg) {
//        log.info("QUEUE03接收消息"+msg);
//    }
//
//    @RabbitListener(queues = "queue_direct04")
//    public void receive04(Object msg) {
//        log.info("QUEUE04接收消息"+msg);
//    }

    /**
     * 秒杀模块 下单操作
     */

    @RabbitListener(queues = "seckillQueue")
    public void receive(String message) {
        log.info("接收到的消息"+message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodId = seckillMessage.getGoodId();
        User user = seckillMessage.getUser();
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodId);
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        // 判断 是否重复抢购
        SeckillOrder seckillOrder  =
                (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId);
        if (seckillOrder != null) {
            return;
        }

        // 下单操作
        orderService.seckill(user, goodsVo);

    }


}
